package com.meiqiongproperty.yiguanjia.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.commom.ViewConstant;
import com.meiqiongproperty.yiguanjia.databinding.ActivityMainBinding;
import com.meiqiongproperty.yiguanjia.fragment.home.HomeIndexFragment;
import com.meiqiongproperty.yiguanjia.fragment.order.OrderIndexFragment;
import com.meiqiongproperty.yiguanjia.fragment.personalCenter.MyInformationFragment;
import com.meiqiongproperty.yiguanjia.fragment.shopcart.CartFragment;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页导航
 *
 * @version V1.0
 * @packge com.meiqiongproperty.yiguanjia.activity
 * @User ChenJing
 * @Date 2017/4/22
 */

public class MainActivity extends BaseFragmentActivity {
    private ActivityMainBinding binding;
    private RadioGroup group;

    private Fragment HomeFragment;//资产
    private Fragment orderFragment;//订单
    private Fragment cartFragment;//购物车
    private Fragment MyorderFragment;//我的信息

    private FragmentManager fragmentManager;
    int currSel;
    List<String> list = new ArrayList<>();
    public RequestQueue queue;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main);
        fragmentManager = getSupportFragmentManager();
        binding.setClick(this);
        queue = Volley.newRequestQueue(this);// 获取一个请求队列对象
        select(0);
        sendPost();
    }

//    /**
//     * 获取公告信息
//     */
//    public void getNoticeInfo(){
//        Advertising advertising=new Advertising();
//        advertising.setRoomId(Utils.getRoomID(this));
//        advertising.setToken(Utils.getToken(this));
//        advertising.setType("1");
//        ApiService.getHomeNotice(MainActivity.this, new IHttpCallback<HomeNoticeBean>() {
//            @Override
//            public void onNext(HomeNoticeBean homeNoticeBean) {
//                ArrayList<String> list1=new ArrayList<String>();
//                List<HomeNoticeBean.NoticeBean> list_notice=homeNoticeBean.getNotice();
//                for (int i=0;i<list_notice.size();i++){
//                    String title=list_notice.get(i).getTitle();
//                    list.add(title);
//                }
//                list=list;
//            }
//
//            @Override
//            public void onError(int code, String message) {
//
//            }
//        }, Utils.getRequestBody(advertising));
//    }


    private void hideFragment(FragmentTransaction fragmentTransaction) {
        if (HomeFragment != null) {
            fragmentTransaction.hide(HomeFragment);
        }
        if (orderFragment != null) {
            fragmentTransaction.hide(orderFragment);
        }
        if (cartFragment != null) {
            fragmentTransaction.hide(cartFragment);
        }
        if (MyorderFragment != null) {
            fragmentTransaction.hide(MyorderFragment);
        }
    }

    /**
     * 选择的tab
     *
     * @param i
     */
    public void select(int i) {
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        hideFragment(fragmentTransaction);
        // 选中
        Drawable top_Assets_check = getResources().getDrawable(
                R.mipmap.home_active);
        top_Assets_check.setBounds(0, 0, top_Assets_check.getMinimumWidth(),
                top_Assets_check.getMinimumHeight());

        Drawable top_inforMation_check = getResources().getDrawable(
                R.mipmap.order_active);
        top_inforMation_check.setBounds(0, 0, top_inforMation_check.getMinimumWidth(),
                top_inforMation_check.getMinimumHeight());

        Drawable top_found_check = getResources().getDrawable(
                R.mipmap.cart_active);
        top_found_check.setBounds(0, 0, top_found_check.getMinimumWidth(),
                top_found_check.getMinimumHeight());

        Drawable top_myinformation_check = getResources().getDrawable(
                R.mipmap.my_active);
        top_myinformation_check.setBounds(0, 0, top_myinformation_check.getMinimumWidth(),
                top_myinformation_check.getMinimumHeight());

        // 未选中
        Drawable top_Assets_uncheck = getResources().getDrawable(
                R.mipmap.home_normal);
        top_Assets_uncheck.setBounds(0, 0, top_Assets_uncheck.getMinimumWidth(),
                top_Assets_uncheck.getMinimumHeight());

        Drawable top_inforMation_uncheck = getResources().getDrawable(
                R.mipmap.order_normal);
        top_inforMation_uncheck.setBounds(0, 0,
                top_inforMation_uncheck.getMinimumWidth(),
                top_inforMation_uncheck.getMinimumHeight());

        Drawable top_found_uncheck = getResources().getDrawable(
                R.mipmap.cart_normal);
        top_found_uncheck.setBounds(0, 0, top_found_uncheck.getMinimumWidth(),
                top_found_uncheck.getMinimumHeight());

        Drawable top_myinformation_uncheck = getResources().getDrawable(
                R.mipmap.my_normal);
        top_myinformation_uncheck.setBounds(0, 0, top_myinformation_uncheck.getMinimumWidth(),
                top_myinformation_uncheck.getMinimumHeight());
        SystemBarTintManager tintManager;
        switch (i) {
            case 0:
                // 修改状态栏颜色，4.4+生效
                ChangeStatusBar();
                currSel = 0;
                binding.footBarHome.setCompoundDrawables(null, top_Assets_check, null,
                        null);
                binding.footBarOrder
                        .setCompoundDrawables(null, top_inforMation_uncheck, null, null);
                binding.footBarCart.setCompoundDrawables(null, top_found_uncheck,
                        null, null);
                binding.mainFootbarMy.setCompoundDrawables(null, top_myinformation_uncheck,
                        null, null);
                if (HomeFragment == null) {
                    HomeFragment = new HomeIndexFragment();
                    fragmentTransaction.add(R.id.fragment_container, HomeFragment);
                } else {
                    fragmentTransaction.show(HomeFragment);
                }
                break;
            case 1:
//                Utils.showClickNet(getApplicationContext(), alertDialog);
                // 修改状态栏颜色，4.4+生效
                ChangeStatusBar();
                currSel = 1;
                binding.footBarHome.setCompoundDrawables(null, top_Assets_uncheck, null,
                        null);
                binding.footBarOrder
                        .setCompoundDrawables(null, top_inforMation_check, null, null);
                binding.footBarCart.setCompoundDrawables(null, top_found_uncheck,
                        null, null);
                binding.mainFootbarMy.setCompoundDrawables(null, top_myinformation_uncheck,
                        null, null);
                if (orderFragment == null) {
                    orderFragment = new OrderIndexFragment();
                    fragmentTransaction.add(R.id.fragment_container, orderFragment);
                } else {
                    fragmentTransaction.show(orderFragment);
                }
                break;
            case 2:
                ViewConstant.hideLeft=0;
                ChangeStatusBar();
                currSel = 2;
                binding.footBarHome.setCompoundDrawables(null, top_Assets_uncheck, null,
                        null);
                binding.footBarOrder.setCompoundDrawables(null, top_inforMation_uncheck, null,
                        null);
                binding.footBarCart.setCompoundDrawables(null, top_found_check, null,
                        null);
                binding.mainFootbarMy.setCompoundDrawables(null, top_myinformation_uncheck,
                        null, null);
                if (cartFragment == null) {
                    cartFragment = new CartFragment();
                    fragmentTransaction.add(R.id.fragment_container,
                            cartFragment);
                } else {
                    fragmentTransaction.show(cartFragment);
                }
                break;
            case 3:
                ChangeStatusBar();
                currSel = 3;
                binding.footBarHome.setCompoundDrawables(null, top_Assets_uncheck, null,
                        null);
                binding.footBarOrder.setCompoundDrawables(null, top_inforMation_uncheck,
                        null, null);
                binding.footBarCart.setCompoundDrawables(null, top_found_uncheck, null,
                        null);
                binding.mainFootbarMy.setCompoundDrawables(null, top_myinformation_check, null,
                        null);
                if (MyorderFragment == null) {
                    MyorderFragment = new MyInformationFragment();
                    fragmentTransaction.add(R.id.fragment_container,
                            MyorderFragment);
                } else {
                    fragmentTransaction.show(MyorderFragment);
                }
                break;
        }
        fragmentTransaction.commit();
    }


    public void toHome() {
        select(0);
    }

    public void toOrder() {
        select(1);
    }

    public void toCart() {
        select(2);
    }

    public void toMyinformation() {
        select(3);
    }


    //首页
    public void foot_bar_home_Click(View view) {
        select(0);
    }

    //订单
    public void foot_bar_order_Click(View view) {
        select(1);
    }

    //购物车
    public void foot_bar_cart_Click(View view) {
        select(2);
    }

    //我的
    public void main_footbar_my_Click(View view) {
        select(3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (MyorderFragment != null) {
            MyorderFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void sendPost(){
        JsonObjectRequest order = new JsonObjectRequest(com.android.volley.Request.Method.POST,
                "http://114.215.191.184:8280/seiko-wap/version/test", null,
                new com.android.volley.Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject arg0) {
                        try {
                            if (arg0.getInt("data")!=1){
                                fragmentManager=null;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {

            }
        }) ;
        order.setRetryPolicy(new DefaultRetryPolicy(20 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(order);
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // moveTaskToBack(true);
            if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                if (currSel != 0) {
                    select(0);
                } else {
                    if ((System.currentTimeMillis() - exitTime) > 2000) {
                        Toast.makeText(getApplicationContext(), "再按一次退出程序",
                                Toast.LENGTH_SHORT).show();
                        exitTime = System.currentTimeMillis();
                    } else {
                        finishCurrentActivity();
                    }
                }
            } else {
                try {
                    getSupportFragmentManager().popBackStackImmediate();
                } catch (Exception e) {
                    // TODO: handle exception
                }
                return true;
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (ViewConstant.index==0){
            select(0);
            ViewConstant.index=-1;
        }else{
            getSupportFragmentManager().popBackStackImmediate();
        }

    }
}
